<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// 新版班牌接口
class Brand_api_v3 extends BaseController {

	public function __construct() {
        parent::__construct();
    }

    // 获取班牌当天课表和考试
    public function get_today_course_data($brandId) {
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info_include_delete($brandInfo['class_id']);
  
        if(empty($classInfo) || $classInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取学校信息
        $schoolInfo = $this->schoolModel->get_school_info($classInfo['school_id']);
        if($schoolInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取年级信息
        $gradeInfo = $this->classesModel->get_grade_info($classInfo['grade_id']);
        if($gradeInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取教师列表
        $teacherParams['schoolId'] = $classInfo['school_id'];
        // 过滤软删除
        $teacherParams['isDelete'] = 0;
        $allTeacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $allTeacherList = array_value_to_key($allTeacherList, 'id');

        // 获取班级列表
        $classParams['schoolId'] = $classInfo['school_id'];
        // 过滤软删除
        $classParams['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'id');

        $scheduleParams['schoolId'] = $classInfo['school_id'];
        $scheduleParams['campusId'] = $classInfo['campus_id'];
        // 只取本周的
        $scheduleParams['isThisWeek'] = 1;
        // 过滤已删除
        $scheduleParams['isDelete'] = 0;
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);

        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($brandInfo['school_id'], $brandInfo['campus_id']);
        if(!$onlyOneSchedule) {
            // 年级作息的天数和节数相同，取本年级的星期一作息即可
            $mondayGradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], 1);
            if($mondayGradeSchedule) {
                $scheduleList = array($mondayGradeSchedule);
            } else {
                $scheduleList = array($scheduleList[0]);
            }
        }
        // var_export($scheduleList);exit;
        $weekLesson = array();
        $schedule = array();
        if(isset($scheduleList[0])) {
            $schedule = $scheduleList[0];
            $scheduleSetting = json_decode($schedule['schedule_time_json'], true);
            // 周几
            $scheduleWeekIndex = date('w') != 0 ? date('w') : 7;

            // // 河西学校返回周五课程
            // if($brandInfo['school_id'] == 32) {
            //     $scheduleWeekIndex = 5;
            // }


            // 判空
            if(!empty($scheduleSetting)){
                $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
                // 生成全部课程时间点
                for($i = 1; $i <= $schedule['schedule_week_days']; $i ++) {

                    // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
                    if(!$onlyOneSchedule) {
                        // 获取当天的年级作息
                        $gradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], $i);
                        if($gradeSchedule) {
                            $scheduleSetting = json_decode($gradeSchedule['schedule_time_json'], true);
                            $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
                        }
                    }

                    foreach($scheduleSetting as $lessonTime) {
                        // 只获取当天
                        if($i != $scheduleWeekIndex) {
                            continue;
                        }

                        $lsData['weekIndex'] = $i;
                        $lsData['classIndex'] = $lessonTime['timeslotInDay'];
                        // 旧版上课时间
                        $lsData['startTime'] = $lessonTime['beginTime'];
                        $lsData['endTime'] = date("H:i", strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60);

                        // 新版上课时间
                        $lsData['startTimeNew'] = $lessonTime['beginTime'] . ':00';
                        $lsData['endTimeNew'] = date("H:i", strtotime($lessonTime['beginTime']) + ($lessonTime['duration'] - 1) * 60) . ':59';
                        if(!isset($lessonTime['sign_interval'])) {
                            // 如未设置，默认为10
                            $lessonTime['sign_interval'] = 10;
                        }

                        // // 兼容身份证
                        // $lsData['startTimeNew'] = date("H:i", strtotime($lessonTime['beginTime']) - $lessonTime['sign_interval'] * 60);
                        // $lsData['endTimeNew'] = $lessonTime['beginTime'];

                        // 考勤时间
                        if($lessonTime['sign_interval'] == 0) {
                            $lsData['signStartTime'] = '';
                            $lsData['signEndTime'] = '';
                        } else {
                            $lsData['signStartTime'] = date("H:i", strtotime($lessonTime['beginTime']) - ($lessonTime['sign_interval']) * 60) . ':00';
                            // 添加0-10秒偏移量
                            $lsData['signStartTime'] = date("H:i:s", strtotime($lsData['signStartTime']) + rand(0, 10));

                            $lsData['signEndTime'] = date("H:i", strtotime($lessonTime['beginTime']) - 60) . ':59';
                        }

                        $lsData['lessonName'] = $lsData['teacherName'] = '';
                        $lsData['teacherList'] = array();

                        $lessonKey = $i. $lsData['classIndex'];

                        // // // 返回sign_interval，供走班情况判断
                        // $lsData['sign_interval'] = $lessonTime['sign_interval'];

                        $weekLesson[$lessonKey] = $lsData;
                    }
                }
            }
            // 获取全校科目列表
            $subjectParams['schoolId'] = $schoolInfo['id'];
            $subjectParams['isDelete'] = 0;
            $subjectList = $this->schoolModel->get_lesson_list($subjectParams);
            $subjectList = array_value_to_key($subjectList, 'lesson_name');
            // 获取课程表课程
            // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
            // 年级不同作息，不需要传schedule_id
            if($onlyOneSchedule) {
                $lessonParams['scheduleId'] = $schedule['id'];
            }
            $lessonParams['classId'] = $classInfo['id'];
            $lessonParams['classroom'] = $classInfo['classroom_id'];
            // // 只获取当天
            $lessonParams['weekIndex'] =  $scheduleWeekIndex;
            $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
            foreach($lessonList as $lesson) {
                $classLesson = $lesson['schedule_lesson'];
                
                // 课程模式和课程图片
                $lessonMode = '上课模式';
                $lessonImg = 'https://resource.rongmixiao.com/default/classTime.png';
                if(isset($subjectList[$classLesson])) {
                    $subjectInfo = $subjectList[$classLesson];
                    if(trim($subjectInfo['lesson_mode'])) {
                        $lessonMode = trim($subjectInfo['lesson_mode']);
                    }
                    if(trim($subjectInfo['lesson_img'])) {
                        $lessonImg = trim($subjectInfo['lesson_img']);
                    }
                }

                // 写入课程名称
                $lessonKey = $lesson['schedule_week_index']. $lesson['schedule_class_index'];
                $weekLesson[$lessonKey]['id'] = $lesson['id'];
                $weekLesson[$lessonKey]['lessonName'] = $classLesson;
                // 课程模式和课程图片
                $weekLesson[$lessonKey]['lessonMode'] = $lessonMode;
                $weekLesson[$lessonKey]['lessonImg'] = $lessonImg;
                // 支持多个授课老师（判断是否开启教师考勤）
                if(!empty($lesson['schedule_teacher'])) {
                    $scheduleTeacherIdArr = explode(',', $lesson['schedule_teacher']);
                    $scheduleTeacherNameArr = array();
                    $scheduleTeacherArr = array();
                    foreach($scheduleTeacherIdArr as $scheduleTeacherId) {
                        if(isset($allTeacherList[$scheduleTeacherId])) {
                            array_push($scheduleTeacherNameArr, $allTeacherList[$scheduleTeacherId]['realname']);
                        }
                        if(isset($allTeacherList[$scheduleTeacherId])) {
                            array_push($scheduleTeacherArr, array(
                                'id' => $allTeacherList[$scheduleTeacherId]['id'],
                                'realname' => $allTeacherList[$scheduleTeacherId]['realname'],
                                'headimgurl' => $allTeacherList[$scheduleTeacherId]['headimgurl'],
                            ));
                        }
                    }
                    $weekLesson[$lessonKey]['teacherName'] = implode('，', $scheduleTeacherNameArr);

                    $weekLesson[$lessonKey]['teacherList'] = $scheduleTeacherArr;
                }
            }
        
            // 课时数组
            $periodArr = array();
            if($scheduleList[0]) {
                $earlyMorningNum = $scheduleList[0]['schedule_early_morning_number'];
                $nightNum = $scheduleList[0]['schedule_night_number'];
                $lessonNum = $scheduleList[0]['schedule_morning_number'] + $scheduleList[0]['schedule_afternoon_number'];
                for($i = 1; $i <= $earlyMorningNum; $i ++) {
                    $periodArr[] = '';
                }
                for($i = 1; $i <= $lessonNum; $i ++) {
                    $periodArr[] = $i;
                }
                for($i = 1; $i <= $nightNum; $i ++) {
                    $periodArr[] = '';
                }
            }
            // var_export($weekLesson);exit;
            foreach($weekLesson as $key => &$value) {
                // 是否重新考勤，默认为false
                $defaultRefreshSign = false;
                // 过滤已删除
                if(!isset($value['weekIndex']) || !isset($value['classIndex'])) {
                    unset($weekLesson[$key]);
                    continue;
                }
                if(empty($value['lessonName'])) {
                    // 判断是否走班
                    $scheduleLesson = $this->classesModel->get_schedule_lesson_info($schedule['id'], $value['weekIndex'], $value['classIndex'], $classInfo['classroom_id']);
                    // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
                    // 年级不同作息，不需要传schedule_id
                    if(!$onlyOneSchedule) {
                        $scheduleLesson = $this->classesModel->get_schedule_lesson_info_for_grade($value['weekIndex'], $value['classIndex'], $classInfo['classroom_id']);
                    }

                    if($scheduleLesson) {
                        $value['id'] = $scheduleLesson['id'];
                        $value['lessonName'] = '走班';

                        // 课程模式和课程图片
                        $lessonMode = '上课模式';
                        $lessonImg = 'https://resource.rongmixiao.com/default/classTime.png';
                        if(isset($subjectList[$scheduleLesson['schedule_lesson']])) {
                            $subjectInfo = $subjectList[$scheduleLesson['schedule_lesson']];
                            if(trim($subjectInfo['lesson_mode'])) {
                                $lessonMode = trim($subjectInfo['lesson_mode']);
                            }
                            if(trim($subjectInfo['lesson_img'])) {
                                $lessonImg = trim($subjectInfo['lesson_img']);
                            }
                        }
                        $value['lessonMode'] = $lessonMode;
                        $value['lessonImg'] = $lessonImg;

                        // 重新考勤为true
                        $defaultRefreshSign = true;
                        // 支持多个授课老师
                        $scheduleTeacherIdArr = explode(',', $scheduleLesson['schedule_teacher']);
                        $scheduleTeacherNameArr = array();
                        $scheduleTeacherArr = array();
                        foreach($scheduleTeacherIdArr as $scheduleTeacherId) {
                            if(isset($allTeacherList[$scheduleTeacherId])) {
                                array_push($scheduleTeacherNameArr, $allTeacherList[$scheduleTeacherId]['realname']);
                            }
                            if(isset($allTeacherList[$scheduleTeacherId])) {
                                array_push($scheduleTeacherArr, array(
                                    'id' => $allTeacherList[$scheduleTeacherId]['id'],
                                    'realname' => $allTeacherList[$scheduleTeacherId]['realname'],
                                    'headimgurl' => $allTeacherList[$scheduleTeacherId]['headimgurl'],
                                ));
                            }
                        }
                        $value['teacherName'] = implode('，', $scheduleTeacherNameArr);
                        $value['teacherList'] = $scheduleTeacherArr;

                        // var_export($value);exit;
                        // 如进入考勤设置0，走班需固定上课前10分钟进入考勤模式
                        if(empty($value['signStartTime'])) {
                            $value['signStartTime'] = date("H:i", strtotime($value['startTime']) - 10 * 60) . ':00';
                            // 添加0-10秒偏移量
                            $value['signStartTime'] = date("H:i:s", strtotime($value['signStartTime']) + rand(0, 10));

                            $value['signEndTime'] = date("H:i", strtotime($value['startTime']) - 60) . ':59';
                        }
                    }
                }

                // 课时
                if(isset($periodArr[$value['classIndex'] - 1])) {
                    $value['period'] = $periodArr[$value['classIndex'] - 1];
                }
                // 默认值
                $value['isExam'] = false;
                $value['refreshSign'] = $defaultRefreshSign;
                $value['className'] = '';
                $value['signList'] = array();
                unset($value['weekIndex']);

            }          

            // 检查是本周还是下周课程
            $weekLesson = array_values($weekLesson);
        }

        // var_export($weekLesson);exit;
        $classroomId = $classInfo['classroom_id'];
        // 当天考试开始时间和结束时间
        $examTimeArr = array();
        $todayCourse = array();
        // 获取考场对应的课室
        if($classroomId){
            // 获取学校ID
            $examParams['schoolId'] = $classInfo['school_id'];
            // 获取学校ID
            $examParams['campusId'] = $classInfo['campus_id'];
            // 过滤课室
            $examParams['locationId'] = $classroomId;
            // 获取哪些属性
            $examParams['field'] = 'ed.id, ed.location_id, ed.room_no, ed.room_name, ed.inside_teachers, er.day, er.begin, er.end, er.timeslot, er.part_of_day, er.lesson_id, er.grade_id, er.exam_entry_time_before, er.exam_entry_time_after, er.type, er.exam_id';
            // 根据日期排序
            $examParams['orderBy'] = 'day ASC, begin ASC';
            // 日期参数
            $examParams['day'] = date('Y-m-d');
            $list = $this->dataModel->get_exam_room_detail_list($examParams);
            foreach ($list as $key => $val) {
                // 添加星期几属性
                $list[$key]['week'] = date_to_week($val['day']);
                // 添加科目名
                $lessonInfo = $this->schoolModel->get_lesson_info($val['lesson_id']);
                $list[$key]['lesson_name'] = $lessonInfo['lesson_name'];
                // 获取考试位置
                $classroom = $this->classesModel->get_classroom_info($val['location_id'], 1);
                $list[$key]['location'] = isset($classroom['classroom_name']) ? $classroom['classroom_name'] : '';        
                // 移除考试位置id
                unset($list[$key]['location_id']);
                // 计算考试时长
                $duration = get_duration($val['begin'], $val['end']);
                $list[$key]['duration'] = $duration;
                // 获取考试年级
                $list[$key]['grade'] = '';
                if(!empty($val['grade_id'])){
                    $grade = $this->classesModel->get_grade_info($val['grade_id']);
                    $list[$key]['grade'] = $grade['grade_name'];
                    unset($list[$key]['grade_id']);
                }
                // 获取场内监考老师
                $list[$key]['inside_teachers'] = [];
                if(isset($val['inside_teachers'])){
                    $idArr = explode(',', $val['inside_teachers']);
                    $insideTeacherList = array();
                    foreach($idArr as $id) {
                        if(isset($allTeacherList[$id])) {
                            $insideTeacherList[] = array(
                                'id' => $allTeacherList[$id]['id'],
                                'realname' => $allTeacherList[$id]['realname'],
                                'headimgurl' => $allTeacherList[$id]['headimgurl'],
                            );
                        }
                    }
                     // 获取巡考教师列表
                    $list[$key]['inside_teachers'] = $insideTeacherList;
                }
                
                // 转换考试类型为中文
                // 判断是否同时存在等级考和合格考
                $bothHave = false;
                if('chosenExam' === $list[$key]['type']){
                    $queryParams['examId'] = $list[$key]['exam_id'];
                    $queryParams['lessonId'] = $list[$key]['lesson_id'];
                    $queryParams['day'] = $list[$key]['day'];
                    $queryParams['timeslot'] = $list[$key]['timeslot'];
                    $queryParams['type'] = 'studyExam';
                    $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                    if(!empty($queryRes)){
                        $bothHave = true;
                    }
                }
                if('studyExam' === $list[$key]['type']){
                    $queryParams['examId'] = $list[$key]['exam_id'];
                    $queryParams['lessonId'] = $list[$key]['lesson_id'];
                    $queryParams['day'] = $list[$key]['day'];
                    $queryParams['timeslot'] = $list[$key]['timeslot'];
                    $queryParams['type'] = 'chosenExam';
                    $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                    if(!empty($queryRes)){
                        $bothHave = true;
                    }
                }
                $list[$key]['type'] = transform_type($list[$key]['type'], $list[$key]['lesson_name'], $bothHave);
                unset($list[$key]['timeslot']);

                // 计算考勤时间
                $list[$key]['sign_begin_time'] = date('H:i:s', strtotime($val['begin']) - $val['exam_entry_time_before'] * 60);
                $list[$key]['sign_end_time'] = date('H:i:s', strtotime($val['begin']) + $val['exam_entry_time_after'] * 60);

                $list[$key]['isExam'] = true;
            }
            if($list) {
                if($weekLesson) {
                    // 计算当天考试开始时间和结束时间
                    $examTimeArr['beginTime'] = $list[0]['sign_begin_time'];
                    $examTimeArr['endTime'] = $list[count($list) - 1]['end'] . ':00';
        
                    $examInsertIndex = 0;
                    if($examTimeArr) {
                        // 当天存在考试
                        foreach($weekLesson as $value2) {
                            // 兼容签到分钟为0的
                            $lessonBeignTime = $value2['signStartTime'] ? $value2['signStartTime'] : $value2['startTimeNew'];
                            $lessonEndTime = $value2['endTimeNew'];

                            if(($lessonBeignTime < $examTimeArr['beginTime'] && $lessonEndTime <= $examTimeArr['beginTime'])) {
                                $todayCourse[] = $value2;
                            } elseif($lessonBeignTime >= $examTimeArr['endTime'] && $lessonEndTime > $examTimeArr['endTime']) {
                                $todayCourse[] = $value2;
                                if($examInsertIndex == 0) {
                                    $examInsertIndex = $value2['classIndex'];
                                }
                            }
                        }

                        if(empty($todayCourse)) {
                            // 只有考试
                            $todayCourse = $list;
                        } else {
                            // $spliceIndex = count($todayCourse) - 1; // 插入位置，初始值为-1：插入到最后
                            $spliceIndex = - 1; 
                            foreach($todayCourse as $key => $value) {
                                // 获取上课开始时间
                                // 兼容签到分钟为0的
                                $lessonBeignTime = $value['signStartTime'] ? $value['signStartTime'] : $value['startTimeNew'];
                                // 上课开始时间大于考试结束时间
                                if($lessonBeignTime >= $examTimeArr['endTime']) {
                                    // 插入考试的位置
                                    $spliceIndex = $key;
                                    break;
                                }
                            }

                            $tempArr = array();
                            foreach($todayCourse as $key => $value) {
                                if($key == $spliceIndex) {
                                    foreach($list as $examItem) {
                                        $tempArr[] = $examItem; 
                                    }
                                }
                                $tempArr[] = $value;
                            }
                            if($spliceIndex == -1) {
                                // 插入到最后
                                foreach($list as $examItem) {
                                    $tempArr[] = $examItem; 
                                }
                            }
                            // 赋值
                            $todayCourse = $tempArr;
                        }
                    }
                } else {
                    $todayCourse = $list;
                }
            }
        }
        // 重新获取字段
        $tempArr = $todayCourse ? $todayCourse : $weekLesson;
        $ret = array();
        // var_export($lessonList);exit;
        foreach($tempArr as $tempkey => $tempValue) {
            // 有考试情况，classindex重新排序
            if($examTimeArr) {
                $classIndex = $tempkey + 1;
            } else {
                $classIndex = $tempValue['period'];
            }
            // // classindex重新排序
            // $classIndex = $tempkey + 1;
            if($tempValue['isExam']) {
                $startTime = $tempValue['begin'] . ':00';
                $endTime = $tempValue['end'] . ':00';
                $signStartTime = $tempValue['sign_begin_time'];
                $signEndTime = $tempValue['sign_end_time'];
                $lessonName = $tempValue['lesson_name'];
                // 如果考试时间短于考试签到时间
                if($signEndTime > $endTime) {
                    $signEndTime = $endTime;
                }
                // 巡考老师
                $teacherList = $tempValue['inside_teachers'];
            } else {
                $startTime = $tempValue['startTimeNew'];
                $endTime = $tempValue['endTimeNew'];
                $signStartTime = $tempValue['signStartTime'];
                $signEndTime = $tempValue['signEndTime'];
                // $teacherName = $tempValue['teacherName'] ? array($tempValue['teacherName']) : array();
                $teacherList = $tempValue['teacherList'] ? $tempValue['teacherList'] : array();
                $lessonName = $tempValue['lessonName'];
            }
            $ret[] = array(
                "id"=> isset($tempValue['id']) ? $tempValue['id'] : '',
                "classIndex"=> (string) $classIndex,
                "startTime"=> $startTime,
                "endTime"=> $endTime,
                "signStartTime"=> $signStartTime,
                "signEndTime"=> $signEndTime,
                "lessonName"=> $lessonName,
                // "teacherName"=> $teacherName,
                "teacherList"=> $teacherList,
                "isExam"=> $tempValue['isExam'],
                "refreshSign"=> isset($tempValue['refreshSign']) ? $tempValue['refreshSign'] : true, // 考试需要重新签到
                "className"=> isset($tempValue['className']) ? $tempValue['className'] : '', // 考试需要重新签到
                "signList"=> isset($tempValue['signList']) ? $tempValue['signList'] : array(),
                'lessonMode' => isset($tempValue['lessonMode']) ? $tempValue['lessonMode'] : '',
                'lessonImg' => isset($tempValue['lessonImg']) ?  $tempValue['lessonImg'] : ''
            );
        }
        // 离线考勤
        // var_export($ret);exit;
        // 获取学生列表
        $schoolStuParams['schoolId'] = $classInfo['school_id'];
        // 过滤软删除
        $schoolStuParams['isDelete'] = 0;
        $schoolStuList = $this->schoolModel->get_student_list($schoolStuParams);
        $schoolStuList = array_value_to_key($schoolStuList, 'id');
        // 获取学生列表
        $schoolStuParams['schoolId'] = $classInfo['school_id'];
        // 过滤软删除
        $classParams['isDelete'] = 0;
        $classParams['schoolId'] = $classInfo['school_id'];
        $classParams['campusId'] = $classInfo['campus_id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'id');
        // 作息
        $refreshClassIndexArr = array(); // 重新考勤节次
        if($schedule) {
            $timeArr = json_decode($schedule['schedule_time_json'], true);
            if($timeArr) {
                foreach($timeArr as $key => $item) {
                    if(isset($item['refresh']) && $item['refresh'] == '是') {
                        array_push($refreshClassIndexArr, $key + 1);
                    }
                }
            }
        }
        // 获取签到的学生
        $classStudentTempArr = array();
        foreach($ret as $key => $item) {
            if($item['id']) {
                if($item['isExam']) {
                    // 考试
                    $examRoomDetailId = $item['id'];
                    $examRoomDetailParams['field'] = 'ed.students, ed.room_name';
                    $examRoomDetailInfo = $this->dataModel->get_exam_room_detail_info($examRoomDetailId, $examRoomDetailParams);
                    $examStudentArr = array();
                    // 获取考场学生
                    if($examRoomDetailInfo && $examRoomDetailInfo['students']) {
                        $studentArr = json_decode($examRoomDetailInfo['students'], true);
                        foreach($studentArr as $item) {
                            if(isset($schoolStuList[$item['userID']])) {
                                // echo'<pre>'; var_export($schoolStuList[$item['userID']]);exit;
                                array_push($examStudentArr, array(
                                    "id" => $schoolStuList[$item['userID']]['id'],
                                    "realname" => $schoolStuList[$item['userID']]['realname'],
                                    "realcard" => $schoolStuList[$item['userID']]['realcard'],
                                    "headimgurl" => $schoolStuList[$item['userID']]['headimgurl'],
                                    "faceImage" => $schoolStuList[$item['userID']]['face_image'],
                                    // "refreshSign" => true, // 是否重新考勤
                                    "userType" => USER_TYPE_STUDENT,
                                    // "shenfenzheng" => $schoolStuList[$item['userID']]['shenfenzheng']
                                ));
                            }
                        }
                    }
                    $ret[$key]['refreshSign'] = true;
                    $ret[$key]['className'] = isset($examRoomDetailInfo['room_name']) ? $examRoomDetailInfo['room_name'] : '';
                    $ret[$key]['signList'] = $examStudentArr;
                } else {
                    // 是否重新考勤
                    $refreshSign = false;
                    // 课程
                    $courseId = $item['id'];
                    $scheduleLessonInfo = $this->classesModel->get_sch_lesson($courseId);
                    $courseStudentList = array();
                    if($scheduleLessonInfo) {
                        if($scheduleLessonInfo['schedule_class_index'] == 1 || in_array($scheduleLessonInfo['schedule_class_index'], $refreshClassIndexArr)) {
                            // 第一节重新考勤
                            $refreshSign = true;
                        } else {
                            // 走班重新考勤
                            if($scheduleLessonInfo['class_id'] != $classInfo['id']) {
                                $refreshSign = true;
                            }
                        }

                        // 判断是否已获取过
                        $scheduleLessonClassId = $scheduleLessonInfo['class_id'];
                        if(isset($classStudentTempArr[$scheduleLessonClassId])) {
                            $courseStudentList = $classStudentTempArr[$scheduleLessonClassId];
                        } else {
                            // 获取上课班级学生
                            $stuParams['isDelete'] = 0;
                            // 兼容身份证
                            $stuParams['classORteach'] = $scheduleLessonClassId;
                            // $stuParams['schoolId'] = $brandInfo['school_id'];
                            $stuParams['field'] = 'id, realname, realcard, headimgurl, face_image AS faceImage';
                            // $stuParams['field'] = 'id, realname, realcard, headimgurl, face_image AS faceImage, shenfenzheng AS shenfenzheng';  // 身份证
                            $courseStudentList = $this->schoolModel->get_student_list($stuParams);
                            $classStudentTempArr[$scheduleLessonClassId] = $courseStudentList;
                        }
                        foreach($courseStudentList as $courseStudentKey => $courseStudentItem) {
                            // $courseStudentList[$courseStudentKey]['refreshSign'] = $refreshSign;
                            $courseStudentList[$courseStudentKey]['userType'] = USER_TYPE_STUDENT;
                        }
                        // 获取上课教师
                        if($schoolInfo['enable_teacher_sign'] == 1 && $scheduleLessonInfo['schedule_teacher']) {
                            $courseTeacherList = array();
                            // 支持多个授课老师
                            $scheduleTeacherIdArr = explode(',', $scheduleLessonInfo['schedule_teacher']);
                            // echo'<pre>'; var_export($scheduleTeacherIdArr);exit;
                            foreach($scheduleTeacherIdArr as $scheduleTeacherId) {
                                if(isset($allTeacherList[$scheduleTeacherId])) {
                                    $courseTeacherList[] = array(
                                        "id" => $allTeacherList[$scheduleTeacherId]['id'],
                                        "realname" => $allTeacherList[$scheduleTeacherId]['realname'],
                                        "realcard" => $allTeacherList[$scheduleTeacherId]['realcard'],
                                        "headimgurl" => $allTeacherList[$scheduleTeacherId]['headimgurl'],
                                        "faceImage" =>  $allTeacherList[$scheduleTeacherId]['face_image'],
                                        // "refreshSign" => true,
                                        "userType" => USER_TYPE_TEACHER
                                    );
                                }
                            }
                            $courseStudentList = array_merge($courseTeacherList, $courseStudentList);
                        }
                        //  echo'<pre>'; var_export($courseStudentList);exit;
                      
                    }
                    $ret[$key]['refreshSign'] = $refreshSign;
                    $ret[$key]['className'] = isset($classList[$scheduleLessonInfo['class_id']]) ? $classList[$scheduleLessonInfo['class_id']]['class_name'] : '';
                    $ret[$key]['signList'] = $courseStudentList;
                }
            }
        }

        // 班级名称限制最长46个字符
        foreach($ret as $key => $item) {
            if($item['className'] && strlen($item['className']) > 46) {
                $ret[$key]['className'] = substr($ret[$key]['className'], 0, 46) . '...';
            }
        }       
        
        exit(json('', true, $ret));
    }
    // 电磁门锁开锁接口
    public function unlock_electr($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');

        // 签到图片，base64与url二选一
        $imageBase64 = $this->post("sign_image", false);
        $imageUrl = $this->post("sign_image_url") ? $this->post("sign_image_url") : '';
        // if(empty($imageBase64) && empty($imageUrl)) {
        //     throw new Exception('图片参数不能为空');
        // }
        // if($imageBase64 && $imageUrl) {
        //     throw new Exception('图片参数错误');
        // }
        if($imageBase64) {
            $imageType = get_img_type_from_base64($imageBase64);
            if(!$imageType) throw new Exception("签到失败，图片参数错误");
        }

        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("签到失败，找不到对应的班牌");
        // 用户类型
        $userType = trim($this->post("user_type"));
        if(empty($userType)) {
            throw new Exception('用户类型参数不能为空');
        }
        // 传卡号优先判断卡号
        if($this->post("cardnum")) {
            $realcard = $this->post("cardnum");
            // 通过卡号获取学生
            $userInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
            $userType = USER_TYPE_STUDENT;
            if(empty($userInfo)) {
                // 通过卡号获取老师
                $userInfo = $this->schoolModel->get_teacher_info_by_realcard($realcard, $brandInfo['school_id']);
                $userType = USER_TYPE_TEACHER;
            }
            if(empty($userInfo)) {
                throw new Exception("卡号不存在");
            }
        } else {
            if($userType == USER_TYPE_STUDENT) {
                // 获取学生信息
                if(empty($this->post('user_id'))) {
                    throw new Exception("签到失败，用户id参数错误");
                }
                $userInfo = $this->schoolModel->get_student_info($this->post('user_id'));
            } else {
                // 获取教师信息
                if(empty($this->post('user_id'))) {
                    throw new Exception("签到失败，用户id参数错误");
                }
                $userInfo = $this->schoolModel->get_teacher_info($this->post('user_id'));
            }
        }
        if(!$userInfo) throw new Exception("签到失败，用户不存在");

        // 获取门锁id
        $lockId = trim($this->post("smart_lock_id"));
        if(empty($lockId)) {
            throw new Exception('门锁id参数错误');
        }
        $smartLockInfo = $this->schoolModel->get_smart_lock_info($lockId);
        if(empty($smartLockInfo)) {
            throw new Exception('门锁id不存在');
        }
        // // 判断白名单
        // $whiteListInfo = $this->schoolModel->get_smart_lock_student_white_list_info_by_student_id($studentInfo['id']);
        // if(empty($whiteListInfo)) {
        //     throw new Exception('没有开锁权限');
        // }
         // 判断1分钟内是否有重复提交
         $recordParams['userId'] = $userInfo['id'];
         $recordParams['userType'] = $userType;
         $recordParams['createtimeMin'] = date("Y-m-d H:i");
         $recordParams['smartLockId'] = $smartLockInfo['id'];
         $recordList = $this->schoolModel->get_smart_lock_unlock_record_list($recordParams);
         if($recordList) {
             // // 测试服不限制
             // if(ENV != 'test' && ENV != 'local') {
                 exit(json('1秒钟内不能重复提交', true));
             // }
         }
        if($imageBase64) {
            // base64
            // 写入图片
            require_once('vendor/autoload.php');
            $fileName = date("Y"). "/". date("m"). "/". date("d"). "/". time(). mt_rand(1000,10000) . ".". $imageType;
            $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
            $client = new Upyun\Upyun($serviceConfig);
            $signImg = UP_URL. $fileName;
            try{
                $result = $client->write("/". $fileName, file_get_contents($imageBase64));   // 上传图片，自动创建目录
            } catch(Exception $e) {
                // 捕获同个图片名，上传多次报错
                throw new Exception("429 Too Many Requests");
            }
    
            // 写文件上传调试日志
            if(!isset($result['x-upyun-width'])) throw new Exception("更新失败，图片参数错误");
        } else {
            // 图片url
            $signImg = $imageUrl;
        }

        // 入库，做个毛线逻辑
        $insert['user_id'] = $userInfo['id'];
        $insert['user_type'] = $userType;
        $insert['username'] = $userInfo['username'];
        $insert['realname'] = $userInfo['realname'];       
        $insert['school_id'] = $brandInfo['school_id'];
        $insert['campus_id'] = $brandInfo['campus_id'];
        $insert['class_id'] = $brandInfo['class_id'];
        $insert['brand_id'] = $brandInfo['id'];
        $insert['scene_img'] = $signImg;
        $insert['smart_lock_id'] = $smartLockInfo['id'];
        $insert['device_id'] = $smartLockInfo['device_id'];
        $insert['createtime'] = date("Y-m-d H:i:s");
        $this->db->insert(SchoolModel::$smartLockUnlockRecordTable, $insert);
        // 返回值
        $ret['name'] = $userInfo['realname'];
        $ret['unlockRecordId'] = $this->db->insert_id();

        exit(json("", true, $ret));
    }

    // 验证授权码接口
    public function verify_license_code(){
        $this->load->model('licenseModel');
        $licenseCode = $this->post("license_code");
        $address = $this->post("address");
        if(empty($licenseCode)) {
            throw new Exception("参数错误，授权码不能为空");
        }
        if(empty($address)) {
            throw new Exception("参数错误，物理地址不能为空");
        }

        // 获取授权码
        $licenseCodeInfo = $this->licenseModel->get_license_code_info($licenseCode);
        if(empty($licenseCodeInfo)) {
            throw new Exception("授权码不存在");
        }
        if($licenseCodeInfo['is_active'] == 1 && $licenseCodeInfo['brand_address'] != $address) {
            throw new Exception("授权码已被使用");
        }
        // var_export($licenseCode);exit;
        // 入库，做个毛线逻辑
        // $data['brand_id'] = $brandId;
        $data['brand_address'] = $address;
        $data['is_active'] = 1;
        if(empty($licenseCodeInfo['activetime'])) {
            $data['activetime'] = date("Y-m-d H:i:s");
        }
        $this->db->update(LicenseModel::$licenseCodeTable, $data, "id='{$licenseCode}'");
        // 返回md5(翻转物理地址)
        $ret = md5(strrev($address));

        exit(json("", true, $ret));
    }

    // 验证服务过期接口
    public function verify_school_expire($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');

        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("签到失败，找不到对应的班牌");
        $schoolInfo = $this->schoolModel->get_school_info($brandInfo['school_id']);
        $ret['expire'] = false;

        $expireSchoolNameArr = array(
            // '测试学校1'
        );
        if(in_array($schoolInfo['school_name'], $expireSchoolNameArr)) {
            $ret['expire'] = true;
        }
        
        exit(json("", true, $ret));
    }

    // 隐藏首页已到和未到人数接口
    public function get_hide_student_sign_school($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');

        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("签到失败，找不到对应的班牌");
        $schoolInfo = $this->schoolModel->get_school_info($brandInfo['school_id']);
        $ret['hide'] = false;
        $schoolNameArr = array(
        );
        if(in_array($schoolInfo['school_name'], $schoolNameArr)) {
            $ret['hide'] = true;
        }
        exit(json("", true, $ret));
    }
}